package com.study01.config;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;

@Configuration
@EnableWebSecurity  //开启springsecurity:之后会默认注册大量的过滤器
//过滤器链模式,责任链模式
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //针对http请求授权
        http.authorizeHttpRequests(authorizeHttpRequests ->
                authorizeHttpRequests.requestMatchers("/login").permitAll()
                        .anyRequest().authenticated()  //其他的所有请求都需要认证
        );

        //loginPage:登录页面
        //loginProcessingUrl:登录接口
        http.formLogin(forlogin ->
                forlogin.loginPage("/login").permitAll()
                        .loginProcessingUrl("/login")
                        .defaultSuccessUrl("/index")
//                        .successHandler(new AuthenticationSuccessHandler() {
//                            @Override
//                            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//                                response.setContentType("text/html;charset=UTF-8");
//                                response.getWriter().write("loginOk");  //登录成功处理器
//                            }
//                        })
//                        .failureHandler(new AuthenticationFailureHandler() {
//                            @Override
//                            public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
//                                response.setContentType("text/html;charset=UTF-8");
//                                response.getWriter().write("loginERROR");  //登录失败处理器
//                            }
//                        })
        ); //登录成功后访问的页面
        http.csrf(Customizer.withDefaults()); //跨域漏洞防御:关闭

        http.cors(Customizer.withDefaults());//跨域拦截关闭

        //退出
        http.logout(logout -> logout.invalidateHttpSession(true)); //退出后删除session

        return http.build();
    }

}
